package yxy.cherry.data.dfa;

import java.util.HashMap;
import java.util.Map;

public class WordNode {
	private Character character;
	private Map<Character, WordNode> sub;
	private boolean end;

	public WordNode addChar(Character character) {
		if (sub == null) {
			sub = new HashMap<>();
		}
		WordNode node = sub.get(character);
		if (node != null) {
			return node;
		}
		node = new WordNode();
		node.character = character;
		sub.put(character, node);
		return node;
	}

	public void addEnd(Character character) {
		if (sub == null) {
			sub = new HashMap<>();
		}
		WordNode node = sub.get(character);
		if (node != null) {
			node.end = true;
			return;
		}
		node = new WordNode();
		node.character = character;
		node.end = true;
		sub.put(character, node);
	}

	public boolean isEnd() {
		return end;
	}

	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		if (character != null) {
			sb.append(character);
		}
		if (end) {
			sb.append("end");
		}
		if (sub != null) {
			sb.append(sub.toString());
		}
		return sb.toString();
	}

	public WordNode getSubNode(Character character) {
		if (sub == null) {
			return null;
		}
		return sub.get(character);
	}
}
